<!--
 @description 购物车
 @fileName index.vue
 @author zengqiongying
 @created 2022/07/27 11:15:55
-->
<template>
  <div class="cart-page" :style="{'padding-top':(topHeight + 48) + 'px','padding-bottom':bottomHeight + 'px'}">
    <Tabbar v-if="!enbleBack" @refresh="refreshPage" />
    <div ref="top" class="cart-header">
      <MineHeader show-statusbar title="购物车" bg-color="transparent" :arrow="enbleBack" />
      <div class="opt-area">
        <template v-if="editState">
          <div class="btn" @click="handleChangeEdit(false)">完成</div>
        </template>
        <template v-else>
          <div class="btn" @click="handleOpenDiscount">折扣</div>
          <div class="btn" @click="handleChangeEdit(true)">编辑</div>
        </template>
      </div>
    </div>
    <div class="gradient-layer" :style="{'top':topHeight + 'px'}" />
    <div class="cart-body">
      <div class="cart-content">
        <List
          ref="list"
          :class="{'cart-list-scroll':list.length>0}"
          :finished.sync="finished"
          :reset-fun="resetData"
          :load="load"
          :refresh="load"
        >
          <CartItem
            v-for="(pro,i) in list"
            ref="cartItem"
            :key="i"
            :cart-data="pro"
            :dis-edit.sync="disEdit"
            @del="handleDel"
            @checked="handleChecked"
            @change="getTotalPrice"
            @open="handleOpenSwipe(pro.id)"
            @click.native="handleClickItem(pro.id)"
          />
        </List>
        <CartEmpty v-if="list.length===0 && finished" :top-margin="topHeight + 5" :bottom-margin="bottomHeight + 16 " />
      </div>
    </div>
    <div v-if="list.length" class="cart-bottom" :class="{'fixed-bottom':enbleBack}">
      <div class="check" :class="{'checked':checkAll}" @click="handleCheckAll">全选</div>
      <template v-if="editState">
        <div class="btn-submit green" @click="handleDeleteAll">删除商品</div>
      </template>
      <template v-else>
        <div class="total-price">合计：<span class="price">{{ totalPrice }}</span></div>
        <div class="btn-submit" @click="handleSettle">结算</div>
      </template>
    </div>
    <Discount
      v-if="showDiscount"
      :show.sync="showDiscount"
      :ids="discountIds"
      @success="handleSuccessDiscount"
    />
    <Popup
      v-model="popupConfig.show"
      msg-align="center"
      icon="warning"
      :message="popupConfig.message"
      :show-cancel-button="popupConfig.type==='commit'"
      @confirm="handlePopConfirm"
      @cancel="handlePopCancel"
    />

  </div>
</template>

<script>
import MineHeader from '@/components/MineHeader'
import Tabbar from '@/components/Tabbar'
import Popup from '@/components/Popup'
import CartItem from './components/CartItem'
import CartEmpty from './components/Empty'
import List from '@/components/PageList'
import Discount from './components/Discount'
import { getShoppingCart, deleteShoppingCart, commitCart } from '@/apis/cart'
export default {
  name: 'Cart',
  components: { MineHeader, Tabbar, Popup, List, CartEmpty, CartItem, Discount },
  filters: {},
  mixins: [],
  data() {
    return {
      enbleBack: !!this.$route.query.back, // 是否可以返回
      topHeight: 175, // 顶部的高度
      disEdit: false, // 禁止编辑输入(价格和数量)
      list: [],
      finished: false, // 列表是否加载完成
      totalPrice: 0, // 总价格
      checkAll: false, // 是否全选
      editState: false, // 是否编辑状态
      showDiscount: false, // 是否编辑折扣
      popupConfig: {
        show: false, // 是否提示
        type: '', // 确认结算：commit, 提示 warning
        message: '' // 提示文案
      }
    }
  },

  computed: {
    bottomHeight() {
      let t = 60
      if (this.list.length === 0) {
        t = 0
      }
      return this.enbleBack ? t : 50 + t
    },
    selectedList() {
      return this.list.filter(v => v.checked === true)
    },
    discountIds() {
      return this.selectedList.filter(v => {
        // return !(v.isActivity === 1 || ['03', '05'].includes(v.productFlag))
        return !['03', '05'].includes(v.productFlag)
      }).map(v => v.id)
    },
    checkedIds() {
      return this.selectedList.map(v => {
        return v.id
      })
    }
  },

  created() {

  },
  activated() {
    this.resetPageData()
  },
  deactivated() {
    this.resetConfig()
  },
  beforeDestroy() {
    this.resetConfig()
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        const topHeight = this.$refs.top.offsetHeight
        this.topHeight = topHeight
      }, 100)
    })
  },
  methods: {
    refreshPage(name) {
      if (this.$route.name === name) {
        this.resetPageData()
      }
    },
    resetPageData() {
      if (this.$refs.list) {
        this.$refs.list.resetPageData()
      }
    },
    load(page, rows) {
      const data = {
        page,
        rows
      }
      return getShoppingCart(data).then(res => {
        const records = res.data.records || []
        if (this.checkAll) {
          records.forEach(v => {
            this.$set(v, 'checked', true)
          })
        }
        this.list.push(...records)
        if (this.list.length >= res.data.total) {
          this.finished = true
        }
        this.getTotalPrice()
      })
    },
    resetData() {
      this.list = []
    },
    resetConfig() {
      this.popupConfig = {
        show: false,
        type: '',
        message: ''
      }
      this.editState = false
      this.disEdit = false
      this.showDiscount = false
    },
    // 单选变更
    handleChecked() {
      const flag = this.list.every(v => !!v.checked)
      this.checkAll = flag
      this.getTotalPrice()
    },
    // 全选
    handleCheckAll() {
      this.checkAll = !this.checkAll
      this.list.forEach(v => {
        this.$set(v, 'checked', this.checkAll)
      })
      this.getTotalPrice()
    },
    // 删除所选
    handleDeleteAll() {
      const ids = this.checkedIds
      if (ids.length === 0) {
        this.$toast('请选择需要删除的商品')
        return
      }
      this.$dialog.confirm({
        title: '确认删除',
        message: '您确定要删除当前所选商品吗？'
      }).then(() => {
        deleteShoppingCart(ids).then(res => {
          this.$toast('删除成功')
          this.checkAll = false
          ids.forEach(id => {
            const index = this.list.findIndex(v => v.id === id)
            if (index > -1) {
              this.list.splice(index, 1)
            }
          })
          if (this.list.length === 0) {
            this.editState = false
            this.disEdit = false
            this.totalPrice = 0
          }
        })
      })
    },
    getTotalPrice() {
      let total = 0
      this.list.forEach(v => {
        if (v.checked) {
          let salePrice = Number(v.salePrice || 0)
          if (v.productFlag && ['03', '05'].includes(v.productFlag)) {
            // 赠品标识的商品单价自动为0
            salePrice = 0
          }
          const price = salePrice * Number(v.quantity || 0)
          total += price
        }
      })
      this.totalPrice = Math.floor(total * 100) / 100
    },
    // 删除购物车
    handleDel(shoppingCartId) {
      const index = this.list.findIndex(v => v.id === shoppingCartId)
      if (index > -1) {
        this.list.splice(index, 1)
      }
    },
    // 点击关闭所有的swipe
    handleClickItem(id) {
      const cells = this.$refs.cartItem
      cells.forEach((cell, i) => {
        const { swipeOpen, cartData } = cell
        const shoppingCartId = cartData.id
        if (swipeOpen) {
          cell.closeSwipe()
        }
      })
    },
    // 开启swipe时，只保留一个
    handleOpenSwipe(id) {
      const cells = this.$refs.cartItem
      cells.forEach((cell, i) => {
        const { swipeOpen, cartData } = cell
        if (swipeOpen && id !== cartData.id) {
          cell.closeSwipe()
        }
      })
    },
    /**
     * 切换编辑状态
     * @param {Boolean} flag 状态：true 开启，false 关闭
    */
    handleChangeEdit(flag) {
      this.editState = !!flag
      this.disEdit = !!flag
      if (!flag) {
        this.getTotalPrice()
      }
    },
    // 打开折扣面板
    handleOpenDiscount() {
      if (this.selectedList.length === 0) {
        this.$toast('请选择需折扣的商品')
        return
      }
      if (this.discountIds.length === 0) {
        this.popupConfig = {
          type: 'warning',
          show: true,
          message: '原价为0的商品，不参与折扣'
        }
        return
      }
      this.showDiscount = true
    },
    /**
     * 折扣保存成功
     * 1.折扣计算勾选商品中若含原价为0的商品，则不参与折扣计算
     * 2.折扣逻辑：折扣后单价=原价*折扣*0.1，若折扣后单价含小数，则四舍五入不保留小数
     * */
    handleSuccessDiscount({ discount, ids }) {
      console.log(discount)
      this.list.forEach(v => {
        if (v.checked) {
          const { orangePrice, isActivity } = v
          // && Number(isActivity || 0) !== 1
          if (Number(orangePrice || 0) > 0) {
            const nPrice = Number(orangePrice || 0) * Number(discount) * 0.1
            this.$set(v, 'salePrice', Number(nPrice).toFixed(0))
          }
        }
      })
      this.$nextTick(() => {
        this.getTotalPrice()
      })
    },
    // 结算
    handleSettle() {
      if (this.checkedIds.length === 0) {
        this.$toast('请选择需要结算的商品')
        return
      }
      const list = this.list.filter(v => !!v.checked)
      const isAllGift = list.every(v => ['03', '05'].includes(v.productFlag))
      if (isAllGift) {
        this.popupConfig = {
          type: 'warning',
          show: true,
          message: '当前所选择的商品全为赠品,无法提交！'
        }
        return
      }

      const flagPrice = list.some(v => {
        return !['03', '05'].includes(v.productFlag) && (v.salePrice === 0 || v.salePrice === '0')
      })
      if (flagPrice) {
        this.popupConfig = {
          type: 'warning',
          show: true,
          message: '该订单中包含单价为0且非赠品的商品，无法提交'
        }
        return
      }

      const flag = list.some(v => v.salePrice === 0 || v.salePrice === '0')
      if (list.length < this.list.length) {
        let message = ''
        if (flag) {
          message = '该订单未全部选择购物车中的商品，且该订单中有单价为0的产品，请确认是否提交？'
        } else {
          message = '该订单未全部选择购物车中的商品，请确认是否提交？'
        }
        this.popupConfig = {
          type: 'commit',
          show: true,
          message
        }
        return
      }

      if (flag) {
        this.popupConfig = {
          type: 'commit',
          show: true,
          message: '该订单中有单价为0的产品，请确认是否提交？'
        }
        return
      }
      this.handleConfirmSettle()
    },
    handlePopCancel() {
      /* this.popupConfig = {
        type: '',
        show: false,
        message: ''
      } */
    },
    handlePopConfirm() {
      const onlyWaring = this.popupConfig.type === 'warning'
      this.popupConfig.show = false
      setTimeout(() => {
        this.popupConfig = {
          type: '',
          show: false,
          message: ''
        }
      }, 1000)
      if (onlyWaring) return
      this.handleConfirmSettle()
    },
    // 确定提交结算
    handleConfirmSettle() {
      commitCart().then(res => {
        if (res.success === 1 && res.msg) {
          this.$router.push({
            path: '/orderCommit',
            query: {
              ids: this.checkedIds.join(','),
              settleCode: res.msg
            }
          })
        } else {
          this.$toast('结算异常，请稍后重试！')
        }
      })
    }
  }
}

</script>
<style lang='less' scoped>
.cart-page{
  padding-bottom: 50px;
  box-sizing: border-box;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-image: url(~@/assets/my/bg_cart.png);
  background-repeat: no-repeat;
  background-size:  100% auto;
}
.cart-header{
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
  width: 100%;
  background-image: url(~@/assets/my/bg_cart.png);
  background-repeat: no-repeat;
  background-size:  100% auto;
  /deep/ .header{
    background-color: transparent;
    .h-icon{
      color: #fff !important;
    }
    .content .h-slot .title{
      color: #fff;
      font-size: 20PX;
    }
    .more-close{
      background: rgba(255,255,255,0.6);
      border-radius: 16px;
      border: 1px solid rgba(0,0,0,0.08);
    }
  }
  .opt-area{
    padding: 13px 16px 0px;
    height: 26px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    color: #fff;
    .btn{
      margin-left: 16px;
      line-height: 26px;
      font-size: 14px;
      font-weight: bold;
    }
  }
}
.gradient-layer{
  position: fixed;
  left: 0;
  width: 100%;
  z-index: 1;
  height: 48PX;
  background: linear-gradient(360deg, #F2F4F5 0%, rgba(255,255,255,0) 100%);
}
.cart-body{
  position: relative;
  background: #F5F6F7;
  min-height: 50vh;
  .cart-content{
    position: relative;
    margin-top: -43PX;
    z-index: 1;
  }
  .cart-list-scroll{
    min-height: calc(100vh - 200px);
  }
}
.cart-bottom{
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  z-index:999;
  height: 64PX;
  padding: 12px 16px;
  background: #FFFFFF;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12PX;
  color: #999999;
  line-height: 18PX;
  &.fixed-bottom{
    bottom: 0;
  }
  .check{
    display: flex;
    align-items: center;
    &::before{
      content: '';
      margin-right: 6px;
      width: 20px;
      height: 20px;
      border: 2px solid #D2D2D2;
      border-radius: 50%;
      box-sizing: border-box;
      background: #fff;
    }
    &.checked::before{
      background:url(~@/assets/my/checked.png) no-repeat;
      background-size: 20px 20px;
      border: 0;
    }
  }
  .btn-submit{
    margin-left:10px;
    width: 100px;
    height: 40PX;
    background: linear-gradient(180deg, #F6945F 0%, #EA5B31 100%);
    border-radius: 21PX;
    color: #FFFFFF;
    font-weight: bold;
    font-size: 14PX;
    line-height: 40PX;
    text-align: center;
    letter-spacing: 1px;
    &.green{
      background: linear-gradient(90deg, #00D5C0 0%, #05C4C3 100%);
    }
  }
  .total-price{
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    .price{
      display: flex;
      align-items: center;
      font-size: 20PX;
      font-weight: 500;
      color: #EA5B31;
      line-height: 28PX;
      &::before{
        content: '¥';
        font-size: 12PX;
        margin-right: 4px;
      }
    }
  }
}
</style>
